package com.bwie.system.mq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bwie.common.constants.Constants;
import com.bwie.common.domain.request.SnatchRedPacketSuccessQueueReq;
import com.bwie.common.exceptions.BizException;
import com.bwie.system.utils.SendSmsUtils;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.xml.crypto.Data;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Author Junchen_N1
 * @Date 2025/6/17 16:45
 * @ClassName SnatchRedPacketConsumer
 * @Description TODO
 */
@Component
public class SnatchRedPacketConsumer {

    @Autowired
    private SendSmsUtils sendSmsUtils;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 用户抢红包异步消费发送消息
     * @param objectMessage
     * @param message
     * @param channel
     */
    @RabbitListener(queuesToDeclare = @Queue(Constants.SNATCH_SUCCESS_QUEUE))
    public void snatchRedPacket(String objectMessage, Message message, Channel channel){
        //获取消息序号
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        SnatchRedPacketSuccessQueueReq snatchRedPacketSuccessQueueReq = JSONObject.parseObject(objectMessage, SnatchRedPacketSuccessQueueReq.class);
        if (Boolean.TRUE.equals(redisTemplate.hasKey(Constants.SNATCH_SUCCESS_QUEUE_UUID + snatchRedPacketSuccessQueueReq.getUuid()))){
            throw new BizException("消息重复消费");
        }
        sendSmsUtils.sendSms(snatchRedPacketSuccessQueueReq.getTel(), JSON.toJSONString(new HashMap<String,String>(){{
            put("code","恭喜您在"+new Date()+"抢到了"+snatchRedPacketSuccessQueueReq.getPrice()+"元");
        }}));
        //存入redis
        redisTemplate.opsForValue().set(Constants.SNATCH_SUCCESS_QUEUE_UUID+snatchRedPacketSuccessQueueReq.getUuid(),1,30, TimeUnit.SECONDS);
        try {
            //ack手动签收保证消息可靠性
            channel.basicAck(deliveryTag,false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
